package vip.xumy.admin.bmap.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import vip.xumy.admin.bmap.mapper.ILoadWorkMapper;
import vip.xumy.admin.bmap.pojo.CityLocate;
import vip.xumy.admin.bmap.pojo.DownWorker;
import vip.xumy.admin.bmap.pojo.WorkContext;
import vip.xumy.admin.bmap.util.DownloadWorker;
import vip.xumy.core.exception.CoreException;

/**
 * @author:mengyxu
 * @date:2021年10月26日
 */

@Service
public class LoadWorkService {
	@Autowired
	private ILoadWorkMapper loadWorkMapper;
	@Autowired
	private CityLocateService cityLocateService;
	@Autowired
	private DownloadWorker worker;

	public List<DownWorker> history() {
		DownWorker example = new WorkContext();
		example.setStatus(2);
		return loadWorkMapper.list(example);
	}

	public List<DownWorker> waitList() {
		DownWorker example = new WorkContext();
		example.setStatus(0);
		return loadWorkMapper.list(example);
	}

	public DownWorker working() {
		DownWorker example = new WorkContext();
		example.setStatus(1);
		List<DownWorker> list = loadWorkMapper.list(example);
		if (list == null || list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	@Transactional
	public void add(WorkContext context) throws Exception {
		Integer cityId = context.getCity();
		if (cityId == null) {
			throw new CoreException("请选择城市");
		}
		CityLocate city = cityLocateService.get(cityId);
		if (city == null) {
			throw new CoreException("未录入该城市对应经纬度,添加失败");
		}
		context.setCityInfo(city);
		loadWorkMapper.save(context);
		worker.addTask(context);
	}

	public void update(DownWorker context) {
		loadWorkMapper.update(context);
	}

}
